﻿using System;
using System.Xml;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows;

namespace MultiViewer
{
    public class FileTiledImage : TiledImage
    {
        /// <summary>Folder with tiles</summary>
        private string folder;

        /// <summary>Each level is in a folder. Otherwise a flat list of files.</summary>
        private bool inFolders = false;

        public FileTiledImage(string folder)
        {
            this.folder = folder;
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Path.Combine(folder, "Tiles.xml"));

            if (xmldoc.DocumentElement.HasAttribute("inFolders"))
            {
                inFolders = bool.Parse(xmldoc.DocumentElement.Attributes["inFolders"].Value);
            }

            int levelCount = Int32.Parse(xmldoc.DocumentElement.Attributes["levelCount"].Value) - 1;
            minLevel = 0;
            maxLevel = levelCount - 1;
            tileSize = new Size(Int32.Parse(xmldoc.DocumentElement.Attributes["tileWidth"].Value),
                Int32.Parse(xmldoc.DocumentElement.Attributes["tileHeight"].Value));
            entireImage = new Rect(0, 0, (1 << levelCount) * tileSize.Width, (1 << levelCount) * tileSize.Height);
            aspectRatio = 1.0;// entireImage.Width / entireImage.Height;
        }

        public string Folder
        {
            get
            {
                return folder;
            }
        }

        public override BitmapImage GetTile(int row, int col, int level)
        {
            string quadKey = TileToQuadKey(col, (1<<level)-row - 1, level);

            string folder = this.folder;

            if (inFolders && level > 0)
            {
                folder = Path.Combine(folder, level.ToString());
            }

            string path = Path.Combine(folder, quadKey) + ".tif";
            return new BitmapImage(new Uri("file://" + Path.GetFullPath(path)));
        }

        public static string TileToQuadKey(int tx, int ty, int zl)
        {
            if (zl == 0)
                return "0";
            string quad = "";
            for (int i = zl; i > 0; i--)
            {
                int mask = 1 << (i - 1);
                int cell = 1;
                if ((tx & mask) != 0)
                {
                    cell++;
                }
                if ((ty & mask) != 0)
                {
                    cell += 2;
                }
                quad += cell;
            }
            return quad;
        }

        public override void Dispose()
        {
            
        }
    }
}